package com.gaoyi.basemodule.baseUtil;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyFragmentManager {
    protected Fragment mFragment;
    private final List<Fragment> mFragmentList;
    private final FragmentManager mFm;
    private final int mId;

    public MyFragmentManager(FragmentManager fm, int id) {
        this.mFm = fm;
        this.mId = id;
        mFragmentList = new ArrayList<>();
    }

    public void showFragment(int index) {
        Fragment toFragment = getFragment(index);
        if (mFragment != toFragment) {
            FragmentTransaction transaction = mFm.beginTransaction();
            if (mFragment != null) {
                transaction.hide(mFragment);
            }
            mFragment = toFragment;
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(mId, toFragment);
            }
            transaction.commit();
        }
    }

    private Fragment getFragment(int index) {
        return mFragmentList.get(index);
    }

    public void setFragment(Fragment... fragments) {
        mFragmentList.addAll(Arrays.asList(fragments));
    }
}
